package com.qianchang.microfinance.view.hsfaceidentity;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.ToastUtil;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.FaceRecognitionBean;
import com.qianchang.microfinance.bean.FindUserBasicInfoBean;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.credit.data.ContractInfoActivity;
import com.qianchang.microfinance.view.credit.data.ScanFaceActivity;
import com.qianchang.microfinance.view.hsfaceidentity.view.RotaterView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import static com.qianchang.microfinance.utils.HSBitmapUtils.bytesToImageFile;


public class ResultActivity extends BaseActivity implements View.OnClickListener {
    private TextView textView;
    private ImageView mImageView;
    private LinearLayout ll_result_image;
    private ImageView bestImage, envImage;
    private Button nextBut;
    private boolean isConfirml = false;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        init();
    }


    private void init() {
        mImageView = (ImageView) findViewById(R.id.result_status);
        textView = (TextView) findViewById(R.id.result_text_result);
        ll_result_image = (LinearLayout) findViewById(R.id.ll_result_image);
        bestImage = (ImageView) findViewById(R.id.iv_best);
        envImage = (ImageView) findViewById(R.id.iv_env);
        nextBut = (Button) findViewById(R.id.result_next);
        nextBut.setOnClickListener(this);
        Bundle bundle = getIntent().getExtras();
        isConfirml = bundle.getBoolean("isConfirml",false);
        String resultOBJ = bundle.getString("result");

        try {
            JSONObject result = new JSONObject(resultOBJ);

            /**********
             textView.setText(getString(R.string.acquisition_successful));
            int resID = result.getInt("resultcode");
            if (resID == R.string.verify_success) {
                doPlay(R.raw.meglive_success);
            } else if (resID == R.string.liveness_detection_failed_not_video) {
                doPlay(R.raw.meglive_failed);
            } else if (resID == R.string.liveness_detection_failed_timeout) {
                doPlay(R.raw.meglive_failed);
            } else if (resID == R.string.liveness_detection_failed) {
                doPlay(R.raw.meglive_failed);
            } else {
                doPlay(R.raw.meglive_failed);
            }
            **********/

            boolean isSuccess = result.getString("result").equals(getResources().getString(R.string.verify_success));
//            mImageView.setImageResource(isSuccess ? R.drawable.result_success : R.drawable.result_failded);
            if (isSuccess) {
                String delta = bundle.getString("delta");
                Map<String, byte[]> images = (Map<String, byte[]>) bundle.getSerializable("images");

                if (images.containsKey("image_best")) {
                    byte[] bestImg = images.get("image_best");
                    if (bestImg != null && bestImg.length > 0) {
                        Bitmap bestBitMap = BitmapFactory.decodeByteArray(bestImg, 0, bestImg.length);
                        bestImage.setImageBitmap(bestBitMap);
                    }
                }
                if (images.containsKey("image_env")) {
                    byte[] envImg = images.get("image_env");
                    if (envImg != null && envImg.length > 0) {
                        Bitmap envBitMap = BitmapFactory.decodeByteArray(envImg, 0, envImg.length);
                        envImage.setImageBitmap(envBitMap);
                    }
                }
                ll_result_image.setVisibility(View.VISIBLE);

                try {
                    hsUploadFaceFile(bundle);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else {
                ll_result_image.setVisibility(View.GONE);
                doRotate(isSuccess);
            }
//            doRotate(isSuccess);      //2018.1.14注释掉
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent(this, ScanFaceActivity.class);
        startActivity(intent);
    }

    public static void startActivity(Context context, Bundle bundle) {
        Intent intent = new Intent(context, ResultActivity.class);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    private static final int RESULT_FINSH_CODE = 1002;
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.result_next) {
            if(status.equals("1")){
                setResult(RESULT_OK);
                if(isConfirml){         //如果是从认证中心进来验证成功结束
                    finish();
                }else{
                    Bundle bundle = new Bundle();
                    FindUserBasicInfoBean basicInfoBean = new FindUserBasicInfoBean();
                    bundle.putSerializable(ConstantAppInfo.BASIC_INFO_BEAN, basicInfoBean);
                    startActivity(ContractInfoActivity.class, bundle);
                    finish();
                }
            }else{
//                nextBut.setText("返回");
                finish();
            }
        }
    }

    private void doRotate(boolean success) {
        RotaterView rotaterView = (RotaterView) findViewById(R.id.result_rotater);
        rotaterView.setColour(success ? 0xff4ae8ab : 0xfffe8c92);
        final ImageView statusView = (ImageView) findViewById(R.id.result_status);
        statusView.setVisibility(View.INVISIBLE);
        statusView.setImageResource(success ? R.drawable.result_success : R.drawable.result_failded);
        if(success){
            textView.setText("验证成功");
            nextBut.setText("下一步");
        }else{
            textView.setText("验证失败");
            nextBut.setText("返回");
        }

        ObjectAnimator objectAnimator = ObjectAnimator.ofInt(rotaterView, "progress", 0, 100);
        objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        objectAnimator.setDuration(600);
        objectAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                Animation scaleanimation = AnimationUtils.loadAnimation(ResultActivity.this, R.anim.scaleoutin);
                statusView.startAnimation(scaleanimation);
                statusView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        objectAnimator.start();
    }

    private MediaPlayer mMediaPlayer = null;

    private void doPlay(int rawId) {
        if (mMediaPlayer == null)
            mMediaPlayer = new MediaPlayer();

        mMediaPlayer.reset();
        try {
            AssetFileDescriptor localAssetFileDescriptor = getResources().openRawResourceFd(rawId);
            mMediaPlayer.setDataSource(
                    localAssetFileDescriptor.getFileDescriptor(),
                    localAssetFileDescriptor.getStartOffset(),
                    localAssetFileDescriptor.getLength());
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch (Exception localIOException) {
            localIOException.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer != null) {
            mMediaPlayer.reset();
            mMediaPlayer.release();
        }
    }


    /**
     * 上传人脸识别照片
     *
     */

    String status = "-2";
    private void hsUploadFaceFile(Bundle bundle) throws UnsupportedEncodingException {
        if (null == bundle) {
            return;
        }
        Map<String, File> files = new HashMap<>();
        String delta = bundle.getString("delta");
        Map<String, byte[]> images = (Map<String, byte[]>) bundle.getSerializable("images");
        if (images.containsKey("image_best")) {
            byte[] bestImg = images.get("image_best");
            String beastStr = bytesToImageFile(bestImg,"imageBest");
            File file = new File(beastStr);
            String fileName = file.getName();
            files.put(fileName, file);
        }

        if (images.containsKey("image_env")) {
            byte[] envImg = images.get("image_env");
            String path = bytesToImageFile(envImg,"imageEnv");
            File file = new File(path);
            String fileName = file.getName();
            files.put(fileName, file);
        }

        if (images.containsKey("image_action1")) {
            byte[] action1Img = images.get("image_action1");
            String path = bytesToImageFile(action1Img,"imageAction1");
            File file = new File(path);
            String fileName = file.getName();
            files.put(fileName, file);
        }

        if (images.containsKey("image_action2")) {
            byte[] action2Img = images.get("image_action2");
            String path = bytesToImageFile(action2Img,"imageAction2");
            File file = new File(path);
            String fileName = file.getName();
            files.put(fileName, file);
        }

        if (images.containsKey("image_action3")) {
            byte[] action3Img = images.get("image_action3");
            String path = bytesToImageFile(action3Img,"imageAction3");
            File file = new File(path);
            String fileName = file.getName();
            files.put(fileName, file);
        }

        if (images.containsKey("image_action4")) {
            byte[] action3Img = images.get("image_action4");
            String path = bytesToImageFile(action3Img,"imageAction4");
            File file = new File(path);
            String fileName = file.getName();
            files.put(fileName, file);
        }

        Map<String, String> fileParamsMap = new HashMap<>();
        fileParamsMap.put("frontImg", "jpg,png");
        fileParamsMap.put("fileType", "0");
        fileParamsMap.put("isTransform", "false");
        fileParamsMap.put("delta", delta);

        show();

        DMOKHttpUtils.getInstance().uploadFile(this, DMConstant.ApiURL.EXECUTE_FACE_RECOGNITION, fileParamsMap, "uploadFile", files, new RequestCallBack<FaceRecognitionBean>() {

            @Override
            public void onSuccess(JsonResult<FaceRecognitionBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    FaceRecognitionBean  faceRecognitionBean = response.getObject();
                    if(faceRecognitionBean != null){
                        status = faceRecognitionBean.getStatus();
                        if(status.equals("1")){
                            doRotate(true);
                        }else{
                            ToastUtil.getInstant().show(ResultActivity.this, faceRecognitionBean.getMessage());
                            doRotate(false);
                            status = "-2";
                        }
                    }else {
                        ToastUtil.getInstant().show(ResultActivity.this, response.getDescription());
                        doRotate(false);
                        status = "-2";
                    }
                } else {
                    ToastUtil.getInstant().show(ResultActivity.this, response.getDescription());
                    doRotate(false);
                    status = "-2";
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(ResultActivity.this, msg);
                doRotate(false);
                status = "-2";
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }




}